/* eslint-disable react-hooks/exhaustive-deps */
import { FC, memo, useEffect, useState } from 'react'
import React from 'react'
import { LtCarouselWrapper } from './style'

interface IState {
  children?: React.ReactNode
  mode?: 'fade' | 'loop'
  dot: boolean
  autoplay?: boolean
  interval?: number
}

const LtCarousel: FC<IState> = memo((props) => {
  const { children, dot, interval = 5000 } = props
  const childrenCount = React.Children.count(props.children)

  const [currentIndex, setCurrentIndex] = useState(0) // 当前显示的轮播图
  const [isRow, setIsRow] = useState(false) // 是否显示左右箭头

  const [autoTimer, setAutoTimer] = useState<NodeJS.Timeout | null>(null)

  // 点击箭头切换当前显示轮播
  const changeCurrent = (e: React.MouseEvent<HTMLDivElement>, flag: boolean) => {
    if (flag) {
      setCurrentIndex((prev) => (prev === 0 ? childrenCount - 1 : prev - 1))
    } else {
      setCurrentIndex((prev) => (prev === childrenCount - 1 ? 0 : prev + 1))
    }
  }

  // 自动轮播
  const autoPlay = () => {
    if (autoTimer) {
      clearInterval(autoTimer)
    }
    setAutoTimer(
      setInterval(() => {
        setCurrentIndex((prev) => (prev === childrenCount - 1 ? 0 : prev + 1))
      }, interval)
    )
  }

  useEffect(() => {
    autoPlay()
  }, [interval])

  // 鼠标进入
  const mounseEnter = () => {
    setIsRow(true)
    if (autoTimer) {
      clearInterval(autoTimer)
    }
  }

  // 鼠标离开
  const mounseLeave = () => {
    setIsRow(false)
    autoPlay()
  }

  return (
    <LtCarouselWrapper onMouseEnter={mounseEnter} onMouseLeave={mounseLeave}>
      {React.Children.map(children, (child, index) => {
        // 你可以在这里对每个子组件进行操作，例如添加额外的属性
        return (
          <div className={`carousel_item ${index === currentIndex ? 'current' : ''}`}>
            <>{child}</>
          </div>
        )
      })}
      {/* 左右箭头 */}
      {isRow && (
        <div className="row">
          <img
            className="left"
            src={require('./image/left-row.png')}
            alt="左箭头"
            onClick={(e) => changeCurrent(e, true)}
          />
          <img
            className="right"
            src={require('./image/right-row.png')}
            alt="右箭头"
            onClick={(e) => changeCurrent(e, false)}
          />
        </div>
      )}
      {/* 指示器 */}
      {dot && (
        <div className="dot">
          {React.Children.map(children, (child, index) => {
            // 你可以在这里对每个子组件进行操作，例如添加额外的属性
            return <span className="dot_item"></span>
          })}
        </div>
      )}
    </LtCarouselWrapper>
  )
})

export default LtCarousel
